import { _decorator, Component, RigidBody, v3, Vec3, Node } from 'cc';
import { Grid } from '../Astar/Grid/Grid';
import { AStarPathfinder } from '../Astar/AstarPathfinder';
const { ccclass, property } = _decorator;

@ccclass('TankAstar')
export class TankAstar extends Component {

    private grid: Grid;

    private pathfinder: AStarPathfinder;

    private targetNode: Node;

    private vec3: Vec3 = v3();

    Init(grid: Grid, target: Node) {
        this.grid = grid;
        this.pathfinder = new AStarPathfinder(grid);
        this.targetNode = target;
    }

    private currentPath: Vec3[] = [];
    private nextPointIndex = 0;
    private moveSpeed = 5; // 单位/秒



    update(deltaTime: number) {

        this.currentPath = this.pathfinder.findPath(this.node.position, this.targetNode.position);
        this.nextPointIndex = 0;
        if (this.nextPointIndex >= this.currentPath.length) return;

        const targetPos = this.currentPath[this.nextPointIndex];
        const dx = targetPos.x - this.node.position.x;
        const dy = 0;
        const dz = targetPos.z - this.node.position.z;
        const distance = Math.sqrt(dx * dx + dz * dz);

        if (distance < 0.1) {
            this.nextPointIndex++;
            return;
        }

        // 标准化方向向量并移动
        const direction = new Vec3(dx / distance, 0, dz / distance);
        //his.node.getComponent(RigidBody).getLinearVelocity(this.vec3);
        // console.log("速度：", this.vec3);
        // console.log("pos:", node.position)
        this.node.position = this.node.position.add(direction.clone().multiplyScalar(this.moveSpeed * deltaTime));
        // console.log(direction.clone().multiplyScalar(this.moveSpeed * deltaTime));

        // 计算目标旋转角度（绕 y 轴）
        const targetAngle = Math.atan2(direction.x, direction.z) * 180 / Math.PI;
        const currentAngle = this.node.eulerAngles.y;
        const lerpFactor = 0.1; // Adjust this value for faster/slower rotation (0-1)
        const smoothedAngle = currentAngle + (targetAngle - currentAngle) * lerpFactor;
        this.node.setRotationFromEuler(0, smoothedAngle, 0);
    }
}